package com.fcat.common.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fcat.springboot.mybatis.service.impl.TsuantoneBaseServiceImpl;
import com.fcat.base.common.util.ArrayUtil;
import com.fcat.base.common.util.StrUtil;
import com.fcat.common.user.entity.Permission;
import com.fcat.common.user.entity.User;
import com.fcat.common.user.entity.UserRole;
import com.fcat.common.user.mapper.UserRoleMapper;
import com.fcat.common.user.service.*;
import com.fcat.common.user.vo.AdminClientRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserRoleServiceImpl extends TsuantoneBaseServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;
    @Value("${token.realm}")
    private String realm;
    @Value("${token.client}")
    private String client;
    @Value("${token.clientSecret}")
    private String clientSecret;
    @Value("${token.clienId}")
    private String clientId;
    @Resource
    private KeycloakService keycloakService;

    /**
     * 1 删除用户和角色的关联信息
     * 2.新增新的用户关联信息
     * 3.判断是否开通keycloak用户信息
     * 4.如果有keycloak用户信息删除权限更新新的权限
     *
     * @param Authorization
     * @param longs
     * @param user
     * @return
     */
    @Override
    public void updateRoles(String Authorization, List<Long> longs, User user) {
        //首先删除数据库所有用户与角色关联
        delByUserId(user.getId());
        //如果添加新的权限那么就是没有权限
        if (ArrayUtil.isEmpty(longs)) return;
        insertByIdsAndUserId(longs, user.getId());
        //修改新的权限
        updateKeycloakPermissionInfo(Authorization, user.getKeycloakId(), longs);
    }


    public void delByUserId(Long userId) {
        delete(UserRole.builder().userId(userId).build());
    }

    public void insertByIdsAndUserId(List<Long> longs, Long userId) {
        List<UserRole> userRoles = new ArrayList<>();
        longs.forEach(item -> {
            //流式添加
            userRoles.add(UserRole.builder().userId(userId).roleId(item).build());
        });
        //添加新的用户信息
        insertList(userRoles);
    }

    /**
     * 修改keycloak 权限信息
     *
     * @param Authorization token
     * @param keycloakId    用户keycloak的信息
     * @param longs         角色id集合
     * @return
     */
    public boolean updateKeycloakPermissionInfo(String Authorization, String keycloakId, List<Long> longs) {
        //如果用户没有keycloakId 那么就直接退出  有的话  就需要更新keycloak的信息
        if (StrUtil.isBlank(keycloakId)) return true;
        List<AdminClientRole> adminClientRoleList = userService.getListByClientId(Authorization, clientId);
        keycloakService.deleteRoles(adminClientRoleList,  keycloakId,clientId, Authorization);//删除用户权限
        List<AdminClientRole> allocatedRoleList = new ArrayList<>();//用来存储需要添加的权限
        List<Permission> permissionList = permissionService.getListByRoleIds(longs);//根据userid获取数据库所有的权限
        List<String> strList = new ArrayList<>();
        if (!StrUtil.isEmpty(permissionList)) {
            //把所有的权限名的值都赋值到一个集合里面
            for (Permission permission : permissionList) {
                strList.add(permission.getName());
            }
        }
        if (!StrUtil.isEmpty(adminClientRoleList)) {
            //判断用户是否有这个权限有就把这个权限添加到用户中心
            for (AdminClientRole adminClientRole : adminClientRoleList) {
                if (strList.contains(adminClientRole.getName())) {
                    allocatedRoleList.add(adminClientRole);
                }
            }
        }
        //判断用户权限的集合是否为空不为空就直接添加到集合中
        if (!StrUtil.isEmpty(allocatedRoleList)) {
            JSONObject resultObject = keycloakService.allocateRoles(allocatedRoleList,  keycloakId,clientId, Authorization);
        }
        return true;
    }

    @Override
    public List<UserRole> getListByRoleids(List<Long> longs) {
        Example example = new Example(UserRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("roleId", longs);
        return mapper.selectByExample(example);
    }

}